<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )

  SampleTrajectory(v-model="trajectoryShow" :selectionRow="specimenRow")
  distributeEquipment(v-model="equipmentShow" :selectionRow="actualSpecimens" @message-to-parent="onDistributed")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type TableProps,
  type Action,
} from "@scmt/common-components";
import { type QueryPagination, useApi } from "@scmt/core-api";
import {
  type SpecimenEntity,
  type SpecimenQueryParams,
} from "@scmt/api-lis-specimen";
import distributeEquipment from "./distributeEquipment.vue";
import { useRequest } from "@scmt/common-hooks";
import { ESpeimenTableColumnKey, specimenColumns } from "@scmt/api-common";
import SampleTrajectory from "../../components/sampleTrajectory.vue";
import { useGroup } from "../../composable/group";

const $api = useApi();
const queryPramas = reactive<SpecimenQueryParams>({
  outward: 0,
  isInspection: 6,
  signingStartDate: "",
  signingEndDate: "",
  get _tempDate() {
    return [this.signingStartDate, this.signingEndDate];
  },
  set _tempDate(value) {
    [this.signingStartDate, this.signingEndDate] = value || ["", ""];
  },
  pageNum: 1,
  pageSize: 20,
});
const trajectoryShow = ref(false);
const specimenRow = ref<SpecimenEntity[]>([]);

const equipmentShow = ref(false);
const selectionRow = ref<SpecimenEntity[]>([]);
const equipmentSpecimens = ref<SpecimenEntity[]>([]);

onMounted(() => {
  request("tableData");
});

const { request, data, loadingMap } = useRequest(
  {
    tableData: (q: any) => {
      const { _tempDate, ...params } = Object.assign({}, queryPramas, q);
      return $api.lis.specimen.query(params);
    },
  },
  {
    tableData: {
      items: [] as SpecimenEntity[],
      pagination: {
        total: 0,
        pageSize: queryPramas.pageSize,
        pageNum: queryPramas.pageNum,
      },
    },
  }
);

const { getCellClassName, spanMethod, getGroupKey } = useGroup(
  toRef(data, "tableData")
);

const actualSpecimens = computed(() => {
  const selectKeys = Array.from(
    new Set(equipmentSpecimens.value.map((item) => item[getGroupKey(item)]))
  );

  return data.tableData.items.filter((i) =>
    selectKeys.includes(i[getGroupKey(i)])
  );
});

const queryFields: FormItemProps[] = [
  {
    prop: "outpatientNumber",
    label: "业务编号",
  },
  {
    prop: "patientName",
    label: "患者姓名",
  },
  {
    prop: "barcode",
    label: "标本条码",
  },
  {
    prop: "source",
    label: "业务来源",
    as: "select",
    options: {
      loadMethod: () => $api.dict.item.listAsOptions("patient-type"),
    },
  },
  {
    prop: "billingDepartment",
    label: "开单科室",
    as: "select",
    options: {
      render: "office-table",
      loadMethod: $api.upms.org.listAsOptions,
    },
  },
  {
    prop: "specimenTypeId",
    label: "标本类型",
    as: "select",
    options: {
      filterable: true,
      loadMethod: () => {
        return $api.lis.specimen.category.listAsOptions();
      },
    },
  },
  {
    prop: "_tempDate",
    label: "签收时间",
    as: "date",
    options: {
      type: "daterange",
    },
    span: 6,
  },
];

const pageParams = computed<DataPageProps>(() => {
  const headerActions: Action[] = [
    {
      label: "批量下发",
      event: "equipment",
      type: "primary",
      disabled: selectionRow.value.length == 0,
    },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    actions: headerActions,
    columns: 6,
    flex: true,
  };

  return dataPageProps;
});

const tableColumns = computed<TableProps["columns"]>(() => [
  {
    prop: "_selection",
    type: "selection",
    label: "序号",
  },
  {
    prop: "batchNumber",
    label: "批次号",
    width: 170,
  },
  specimenColumns[ESpeimenTableColumnKey.Source],
  specimenColumns[ESpeimenTableColumnKey.OutpatientNumber],
  specimenColumns[ESpeimenTableColumnKey.Barcode],
  specimenColumns[ESpeimenTableColumnKey.State],
  specimenColumns[ESpeimenTableColumnKey.PatientName],
  specimenColumns[ESpeimenTableColumnKey.Sex],
  specimenColumns[ESpeimenTableColumnKey.Age],
  specimenColumns[ESpeimenTableColumnKey.SpecimenTypeId],
  specimenColumns[ESpeimenTableColumnKey.ApplicationProject],
  {
    prop: "collectionName",
    label: "采集医生",
    tooltip: true,
  },
  {
    prop: "collectionTime",
    label: "采集时间",
    format: "datetime",
    sortable: true,
  },
  {
    prop: "sendInspectionTime",
    label: "送检时间",
    format: "datetime",
  },
  specimenColumns[ESpeimenTableColumnKey.Urgent],
  {
    prop: "_operation",
    label: "操作",
    fixed: "right",
    actions: [
      {
        label: "标本轨迹",
        event: "check",
        type: "primary",
      },
      {
        label: "设备下发",
        event: "equipment",
        type: "primary",
      },
    ],
  },
]);
const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: tableColumns.value,
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    onSelectionChange: (selection: any) => {
      selectionRow.value = selection;
    },
    highlightCurrentRow: true,
    cellClassName: getCellClassName,
    spanMethod: spanMethod,
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "check":
      specimenRow.value = model;
      trajectoryShow.value = true;
      break;
    case "equipment":
      equipmentSpecimens.value = model ? [model] : selectionRow.value;
      equipmentShow.value = true;
      break;
  }
};

const onDistributed = () => {
  request("tableData", {
    pageNum: 1,
  });
};
</script>

<style lang="less" scoped>
@text-size: calc(var(--unit) * 20);

:deep(.el-table) {
  &__body {
    .group-text {
      position: relative;

      &::before {
        position: absolute;
        display: inline-block;
        color: var(--el-color-primary);
        font-size: var(--mt-fs-mini);
        top: 50%;
        transform: translate(-50%, -50%);
        content: "合";
        font-weight: 700;
        width: @text-size;
        height: @text-size;
        text-align: center;
        line-height: @text-size;
        border-radius: 50%;
        background-color: var(--el-color-white);
        z-index: 1;
      }
    }

    .group-text--offset {
      position: relative;
      &::before {
        top: -50%;
        transform: translate(-50%, 50%);
      }
    }
  }
}
</style>
